package admin.controllers;

import helpers.IdUniqueHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.CoordinaModel;
import models.OrderModel;
import models.OrderProductModel;
import models.RouteModel;
import models.StaffModel;
import models.StoreItemModel;
import models.TransactionModel;
import admin.data.CoordinaData;
import admin.data.RouteData;
import admin.data.StaffData;
import admin.data.StoreItemData;
import admin.data.TransactionData;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import data.OrderData;


@SuppressWarnings("serial")
public class StoreExportServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		response.setCharacterEncoding("UTF-8");
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String params = path.replaceAll("/admin/store-item/export/", "");	
		ArrayList<CoordinaModel> listCoordina = new ArrayList<CoordinaModel>();	
		if(params.length()>8)
		{
			CoordinaData coordinaData = new CoordinaData();
			CoordinaModel coordinaModel = coordinaData.getById(params);	
			HttpSession session = request.getSession();
			
			if((coordinaModel!=null)&&((session.getAttribute("success")!=null)||(coordinaModel.getStatus()==1)))
			{			
				StaffData staffData = new StaffData();
				StaffModel staff = staffData.getByCode(coordinaModel.getEmployeeId());
				String[] listOrderId = coordinaModel.getListOrder().split(",");
				TreeMap<String, OrderProductModel> mapOrderProduct = new TreeMap<String, OrderProductModel>();
				int totalVC = 0; 
				int totalSP = 0; 
				for (int i = 0; i < listOrderId.length; i++) {
					if(listOrderId[i].length()>9)
					{
						OrderModel orderModel = OrderData.getOrder(listOrderId[i]);
						List<String> listOrderProduct = orderModel.getListOrderProduct();
						for (String stringOrderProduct : listOrderProduct) {
							OrderProductModel orderProduct = new OrderProductModel();
							orderProduct.getValueFromString(stringOrderProduct);	
							if (mapOrderProduct.containsKey(orderProduct.getProductId())) {
								int quantity = mapOrderProduct.get(orderProduct.getProductId()).getQuantity()+orderProduct.getQuantity();
								orderProduct.setStoreType(orderModel.getDealProductType());
								orderProduct.setQuantity(quantity);
							} else {
								orderProduct.setStoreType(orderModel.getDealProductType());
								if(orderModel.getDealProductType()==0) {totalVC++;}
								if(orderModel.getDealProductType()==1) {totalSP++;}
							}
							mapOrderProduct.put(orderProduct.getProductId(), orderProduct);
						}
					}
				}
				
				request.setAttribute("coordinaModel", coordinaModel);
				request.setAttribute("staff", staff);
				request.setAttribute("mapOrderProduct", mapOrderProduct);
				request.setAttribute("totalVC", totalVC);
				request.setAttribute("totalSP", totalSP);
				try {
					request.getRequestDispatcher("/admin/pages/store_export.jsp").forward(request, response);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			else
			{
				session.setAttribute("alert", "Mã tuyến sai hoặc tuyến đã được xác nhận xuất hàng !");				
				response.sendRedirect("/admin/store-item/export/");
			}
		}
		else
		{
			CoordinaData coordinaData = new CoordinaData();
			listCoordina = coordinaData.getCoordina("","1","","","","");
			RouteData routeData = new RouteData();
			TreeMap<String, RouteModel> mapRoute = routeData.getMapRoute();
			request.setAttribute("mapRoute", mapRoute);
			request.setAttribute("listCoordina", listCoordina);
			try {
				request.getRequestDispatcher("/admin/pages/store_export_list.jsp").forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String action = (String) request.getParameter("action");
		String coordinaId = (String) request.getParameter("coordinaId");
		
		if (action.equalsIgnoreCase("search"))
		{
			response.sendRedirect("/admin/store-item/export/"+coordinaId);
		}
		
		if (action.equalsIgnoreCase("saveExport")) {
			CoordinaData coordinaData = new CoordinaData();
			CoordinaModel coordinaModel = coordinaData.getById(coordinaId);;
			coordinaModel.setStatus(2);
			coordinaModel.setCreated(new Date());
			coordinaData.insert(coordinaModel);		
			
			String listOrder = coordinaModel.getListOrder();
			String[] list = listOrder.split(",");
			for (int i = 0; i < list.length; i++) {
				if (list[i].length() > 9) {
					
					Objectify objfy = ObjectifyService.beginTransaction();					 
					
					OrderModel orderModel = OrderData.getOrder(list[i]);
					List<String> listOrderProduct = orderModel.getListOrderProduct();
					for (String stringOrderProduct : listOrderProduct) {
						OrderProductModel orderProduct = new OrderProductModel();
						orderProduct.getValueFromString(stringOrderProduct);
						StoreItemData storeItemData = new StoreItemData();
						StoreItemModel storeItemModel = storeItemData.getItem(orderProduct.getProductId());
						int inventory = storeItemModel.getInventory() - orderProduct.getQuantity();
						storeItemModel.setInventory(inventory);
						int delivery = storeItemModel.getDelivery() + orderProduct.getQuantity();
						storeItemModel.setDelivery(delivery);
						storeItemData.insert(storeItemModel,objfy);
						
						TransactionModel transaction = new TransactionModel();
						transaction.setTransactionId(IdUniqueHelper.getId());
						transaction.setDealId(storeItemModel.getDealId());
						transaction.setStoreItemId(storeItemModel.getId());
						transaction.setInventory(storeItemModel.getInventory());
						transaction.setDelivered(storeItemModel.getDelivered());
						transaction.setDelivery(storeItemModel.getDelivery());
						transaction.setLoc(storeItemModel.getLoc());
						transaction.setType(0);
						transaction.setDate(Calendar.getInstance().getTime());
						transaction.setAmount(orderProduct.getQuantity());
						TransactionData transactionData = new TransactionData();
						transactionData.insert(transaction);
					}					
					objfy.getTxn().commit();
				}
			}			

			HttpSession session = request.getSession();
			session.setAttribute("success", "Xuất hàng theo LOC thành công !");
			
			response.sendRedirect("/admin/store-item/export/"+coordinaModel.getId());
		} 	
	}
}